#!/bin/sh

if [ $# != 2 ]; then
	echo "Usage: $0 <path-to-object> <path-to-source>"
	exit 2
fi

if [ ! -f "$1" ]; then
	echo "Couldn't access object file"
	exit 2
fi

if [ ! -f "$2" ]; then
	echo "Couldn't access source file"
	exit 2
fi

trylines=3
lastline=$(wc -l "$2" | cut -d' ' -f1)
changelog=$(mktemp -u)

cp "$2" "$2.copy" 

(nm -C "$1" | awk 'BEGIN {IGNORECASE=1} $2 == "t" {print $3;}' | cut -d'(' -f1 | sort | uniq) |
	while read -r listline; do
		(egrep -n "${listline}[\s]?\(" "$2.copy") |
			while read -r funcline; do
				linenum=$(echo "$funcline" | cut -d':' -f1)
				case "$funcline" in
					*';'*)
					:
					;;
					*'if'*'('*"$listline"*)
					:
					;;
					*'while'*'('*"$listline"*)
					:
					;;
					*)
					sed -n '1,'$((linenum - 1))'p' "$2.copy" > "$2.copy2"
					for lnum in $(seq $linenum $((linenum + trylines))); do
						sed -n $lnum'p' "$2.copy" | sed 's/{/{ fprintf(stderr, "'"$listline"'\\n");/w '"$changelog" >> "$2.copy2"
						test -s "$changelog" && break
					done
					sed -n $((lnum + 1))','$lastline'p' "$2.copy" >> "$2.copy2"
					mv "$2.copy2" "$2.copy"
					sync
					;;
				esac
			done
	done
